//
//  NetworkService.m
//  ios-loan
//
//  Created by ys on 15/12/2017.
//  Copyright © 2017 hxhg. All rights reserved.
//

#import "NetworkService.h"
#import <AFNetworking/AFNetworking.h>
#import "ALLog.h"
@interface NetworkService()

@property (nonatomic, strong) AFHTTPSessionManager * manager;

@end

@implementation NetworkService

+ (id)sharedInstance{
    static NetworkService * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[NetworkService alloc] init];
    });
    return instance;
}

- (instancetype)init {
    if (self = [super init]) {
        self.manager = [AFHTTPSessionManager manager];
        self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        //https
        AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        securityPolicy.validatesDomainName = YES;
        self.manager.securityPolicy = securityPolicy;
    }
    return self;
}

+ (void)send:(NSMutableURLRequest *)request completionHandler:(void(^)(id responseObj, NSError *error))completion {
    [[NetworkService sharedInstance] send:request completionHandler:completion];
}

+ (void)send:(NSMutableURLRequest *)request
    progress:(void (^)(NSProgress *uploadProgress))uploadProgressBlock completionHandler:(void(^)(id responseObj, NSError *error))completion {
    [[NetworkService sharedInstance] send:request progress:uploadProgressBlock completionHandler:completion];
}

- (void)send:(NSMutableURLRequest *)request completionHandler:(void(^)(id responseObj, NSError *error))completion {
    NSURLSessionDataTask *dataTask = [self.manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        [self sendComplete:response obj:responseObject err:error completionHandler:completion];
    }];
    [dataTask resume];
}

- (void)send:(NSMutableURLRequest *)request
    progress:(void (^)(NSProgress *uploadProgress))uploadProgressBlock
completionHandler:(void(^)(id responseObj, NSError *error))completion {
//    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
//    } error:nil];
//    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [self.manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      if (uploadProgressBlock) {
                          uploadProgressBlock(uploadProgress);
                      }
                  } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      [self sendComplete:response obj:responseObject err:error completionHandler:completion];
                  }];
    [uploadTask resume];
}

- (void)sendComplete:(NSURLResponse * _Nonnull)response
                 obj:(id  _Nullable)responseObject
                 err:(NSError * _Nullable)error
   completionHandler:(void(^)(id responseObj, NSError *error))completion{
    if (error) {
        LogE(@"%@", error);
    }
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
    NSDictionary *responseDic = nil;
    NSError *rError = nil;
    NSInteger code = httpResponse.statusCode;
    if (responseObject) {
        responseDic = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject options:NSJSONReadingMutableContainers error:nil];
    }
    if (code != 200) {
        rError = [NSError errorWithDomain:@"http fail" code:code userInfo:nil];
        LogW(@"http response code: %ld", ((NSHTTPURLResponse *)response).statusCode);
    }
    completion(responseDic, rError);

}

@end
